#include "ResourceManager.h"

#include <SDL.h>
#include <SDL_image.h>
#include <utils/Error.h>
#include <main/Globals.h>

ResourceManager::ResourceManager() {
    loadTexture("butterfly1.png", "player");
	loadTexture("box.png", "box");
	loadTexture("bee_small.png", "beeSmall");
	loadTexture("atlas.png", "atlas", true);
    loadTexture("background.png", "background");
    loadTexture("background0.png", "background0");
    loadTexture("background1.png", "background1");
    loadTexture("background2.png", "background2");
    loadTexture("background3.png", "background3");
    loadTexture("background4.png", "background4");
    loadTexture("background5.png", "background5");
    loadTexture("background6.png", "background6");
    loadTexture("background7.png", "background7");
    loadTexture("mantis_move.png", "mantis");
    loadTexture("shark_move2.png", "shark");
	
	loadTexture("bomb.png", "mine");
	
	loadTexture("puerta2bcerrada.png", "doorClosed");

	// childs
	loadTexture("child0.png", "child0");
	loadTexture("child1.png", "child1");
	loadTexture("child2.png", "child2");
	loadTexture("child3.png", "child3");
	loadTexture("child4.png", "child4");

	// Door
	loadTexture("doorOpening.png", "doorOpening");
	loadTexture("doorClosing.png", "doorClosing");

    // Sounds
    loadSound("addChild.wav", "addChild");
    loadSound("removeChild.wav", "removeChild");
}

ResourceManager::~ResourceManager() {
	for(std::map<std::string, SDL_Texture*>::iterator it = textures.begin(); it != textures.end(); ++it) {
		SDL_DestroyTexture(it->second);
	}

    for(std::map<std::string, Mix_Chunk*>::iterator it = sounds.begin(); 
                                                    it != sounds.end(); 
                                                    ++it) {
        Mix_FreeChunk(it->second);
    }
}

void ResourceManager::loadTexture(const std::string& fileName, const std::string& id, bool isTest) {
	const std::string path = isTest ? "test_media/textures/" : "media/textures/";
	SDL_Texture* texture = IMG_LoadTexture(Globals::gRenderer, (path + fileName).c_str());
	if (!texture) {
		printError("IMG_LoadTexture failed");
	}
	textures[id] = texture;
}

void ResourceManager::loadSound(const std::string& filename, const std::string& id) {
    const std::string path = "media/sounds/";
    Mix_Chunk* chunk = Mix_LoadWAV((path + filename).c_str());

    if (!chunk) {
        printError("Mix_LoadWAV failed");
        assert(false);
    }

    sounds[id] = chunk;
}

SDL_Texture* ResourceManager::getTexture(const std::string& id) {
	assert(textures.find(id) != textures.end());
	return textures[id];
}

Mix_Chunk* ResourceManager::getSound(const std::string& id) {
    assert(sounds.find(id) != sounds.end());
    return sounds[id];
}
	
